package com.voice.server.channel.handle.impl;

import com.voice.core.entity.HttpHeader;
import com.voice.core.connection.Connection;
import com.voice.core.connection.ConnectionStatus;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.connection.impl.SocketChannelConnectionImpl;
import com.voice.server.connection.SdkConnection;
import com.voice.server.connection.map.SdkConnectionMap;
import com.voice.server.publish.PublishHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Slf4j
@Component("/message/echo/success")
public class MessageStreamListenerHandler extends AbstractStreamListenerHandler<SdkConnection> {

    @Autowired
    private SdkConnectionMap connectionMap;
    @Autowired
    private Map<String, PublishHandler> publishHandlerMap;

    @Override
    public SdkConnection conversionTo(HttpHeader requestHeader, Connection connection) throws Exception {
        String appKey=requestHeader.get("appKey",String.class);
        String userId=requestHeader.get("userId",String.class);
        return new SdkConnection((SocketChannelConnectionImpl)connection,userId,appKey);
    }

    @Override
    public void onStatusChange(ConnectionStatus status, SdkConnection connection) {
        switch (status) {
            case CLOSED:
                log.info("客户端SdkConnection:{} 断开",connection);
                connectionMap.remove(connection.getUserId());
                break;
            case AUTHORIZED:
                log.info("客户端SdkConnection:{} 连接",connection);
                connectionMap.put(connection.getUserId(),connection);
                break;
        }
    }

    @Override
    public PublishHandler getPublishHandler(String path) {
        return publishHandlerMap.get(path);
    }
}
